package com.chenhy.tcp_tester;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.FontRequest;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.IllegalFormatCodePointException;
import java.util.List;
import java.util.Set;

import javax.security.auth.login.LoginException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Create By HauyuChen
 * Email：Hauyu.Chen@gmail.com
 */

/* 客户端界面代码 */
public class ClientActivity extends Activity {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private HorizontalListView listview1;
private String a="0x";
private  String st=null;
    private  String tp=null;
    private String pinjie2;
    private int count=0;
    private int position=0;
    private String zx;
    private StringBuffer p2=new StringBuffer();
private IntentFilter intentFilter;
    private final Object lock = new Object();

    private boolean pause = false;
private byte[] test= new byte[]{};
private List list8=new ArrayList(){};
  //  test=new byte[]{(byte)0xA0,(byte)0x04,(byte)0x01,(byte)0x74,(byte)0x00,(byte)0xE6};
    private String t1;
    private String[]list7=new String[]{"A004017400E7","A004018001DA","A004017401E6","A004018001DA","A004017402E5","A004018001DA","A004017403E4","A004018001DA","A0030190CC"};

 //           "A004017404E3","A004018001DA","A004017405E2","A004018001DA","A004017406E1","A004018001DA","A004017407E0","A004018001DA","A0030190CC"};
private InputStreamReader isr;
private BufferedReader br;
                               
int p11=0;
private  Message msg;
private  static  final  int UPdate=1;
    private  static  final  int UPdate2=10;
private static  final int panduan=2;
    private static  final int panduan2=20;
private  static  final  int baocuo=3;
    private  static  final  int baocuo2=30;
private static  final    int wflj=1001;
private  static final int ljcw=1002;
private static  final   int dzcw=1003;
private static  final   int ljyc=1004;
private  String IPAdr,IPAdr2;
private  int   PORT,PORT2;

    private   String  hexString="A0030172EA";

    private String[] partarr = new String[]{"101000000000000000000021", "343138313230303130313031","343138313230303130313032","343138313230303130313033"
            ,"343138313230303130313034","343138313230303130313035","343138313230303130313036","343138313230303130313037","343138313230303130313038","343138313230303130313039"};

    private String[] ceshiarr = new String[]{"343138313230303130313030", "343138313230303130313032","343138313230303130313033","343138313230303130313034"
            ,"343138313230303130313035","343138313230303130313035","343138313230303130313039","343138313230303130313037","343138313230303130313038","343138313230303130313139"

    };

    byte[]sb=hexString.getBytes();

private String bS;
    private byte[]ms=new byte[5];
//    private  byte[]msg1=new byte[5];
//    private  byte[]msg2=new byte[6];
//    private  byte[]msg3=new byte[5];
    private final String TAG="ClientActivity";
    private EditText edit_ip,edit_ip2;
    private TextView txt;
    private EditText edit_port,edit_port2;
    private EditText edit_send;
    private EditText edit_recv;
    private Button btn_connect,btn_connect2;
    private Button btn_send,btn_send1,btn_send2,btn_send3;
    private ScrollView scrollView;
    private boolean isConnected = false;
    private boolean isConnected2 = false;
  private   Socket socket = null;
    private   Socket socket2 = null;
 private    InputStream mBufferedReaderClient=null;
    private    InputStream mBufferedReaderClient2=null;
 private  String   subStr;
private OutputStream writer;
  //  BufferedWriter writer = null;
    BufferedReader reader = null;
    private byte line;
    private int len;
  //  private byte[]buf;
    private String strOutput;
    private String pinjie;
//private String[] nu=null;
    List strList = new ArrayList();
 public static    List  relist=new ArrayList();

    List firstList=new ArrayList();
    List list=new ArrayList();
    List list5=new ArrayList();
    List list4=new ArrayList();
    List list10=new ArrayList();
    List list11=new ArrayList(Arrays.asList("00000000000601050000FF00","00000000000601050001FF00","00000000000601050002FF00","00000000000601050003FF00",
            "00000000000601050004FF00","00000000000601050005FF00","00000000000601050006FF00","00000000000601050007FF00"));
    List list12=new ArrayList(Arrays.asList("000000000006010500000000","000000000006010500010000","000000000006010500020000","000000000006010500030000",
            "000000000006010500040000","000000000006010500050000","000000000006010500060000","000000000006010500070000"));
    private String[]arr1=new String[]{"1585193","180151","1304182","1585193","907277","106439"};
    private String[]arr2=new String[]{"1585193","180151","1304182","1585193","907277","106439"};
    private  String[]DOBHarr=new String[]{"010500FF008C3A","010500010003DDFA01","01050002FF002DFA","01050003FF007C3A",
            "01050004FF00CDFB","01050005FF009C3B","01050006FF006C3B","01050007FF003DFB"};
    private  String[]DODKarr=new String[]{"010500000000CDCA","0105000100009C0A","0105000200006C0A","0105000300003DCA",
            "0105000400008C0B","010500050000DDCB","0105000600002DCB","0105000700007C0B"};
    private  NetworkChangeReceiver networkChangeReceiver;

 dqThread  thread=new dqThread();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
      //  sendRequestWithOkHttp();
        /* 初始化 */
        txt= (TextView) findViewById(R.id.xsarr);
        edit_ip = (EditText) findViewById(R.id.edit_ip);
        edit_ip2=findViewById(R.id.edit_ip2);
        edit_port = (EditText) findViewById(R.id.edit_port);
        edit_port2=findViewById(R.id.edit_port2);
        edit_send = (EditText) findViewById((R.id.edit_msgsend));
        edit_recv = (EditText) findViewById(R.id.edit_recv);
        btn_connect = (Button) findViewById(R.id.btn_connect);
        btn_connect2=findViewById(R.id.btn_connect2);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_send2=findViewById(R.id.btn_send2);
        listview1=  findViewById(R.id.list_view1);
        scrollView=findViewById(R.id.src);
          Fragment cs=new csFragement();
intentFilter=new IntentFilter();
intentFilter.addAction("android.net");
  networkChangeReceiver=new NetworkChangeReceiver();
       registerReceiver(networkChangeReceiver,intentFilter);
       Intent intent=new Intent(ClientActivity.this,MQTTService.class);
        startService(intent);
//connect();
//send();




//        btn_send1 = (Button)findViewById(R.id.btn_send1);
//        btn_send2 = (Button)findViewById(R.id.btn_send2);
//        btn_send3 = (Button)findViewById(R.id.btn_send3);
        /* 连接按钮 */




        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* 连接按钮处理函数 */
                connect();

mq();


            }
        });

        btn_connect2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connect2();


            }
        });

//list11.add(DOBHarr);


btn_send2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        thread.yield();
        Log.e("502","502");

    }
});



        /* 发送按钮 */
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* 发送按钮处理函数 */
                test=new byte[]{(byte)0x01,(byte)0x05,(byte)0x00,(byte)0x01,(byte)0xFF,(byte)0x00,(byte)0xDD,(byte)0xFA};

                send2();

            }
        });
//        btn_send1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                /* 发送按钮处理函数 */
//                send1();
//            }
//        });
//        btn_send2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                /* 发送按钮处理函数 */
//                send2();
//            }
//        });
//        btn_send3.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                /* 发送按钮处理函数 */
//                send3();
//            }
//        });

//        for (String o : arr1) {
//            /*
//             * 筛选出两个数组中相同的值，>= 0 表示相同，< 0 表示不同 。
//             * 有相同值是返回元素的下标值。
//             * 此处采用的是 "二分搜索法来搜索指定数组"。
//             * */
//            if(Arrays.binarySearch(arr2, o) >= 0){
//
//                System.out.println(o);
//            }
//        }


        //    Log.e("CCC", "cc"+Arrays.binarySearch(partarr,strList.toArray())>=0);


//         for (int i=0;i<arr1.length;i++){
//             for (int j=0;j<arr2.length;j++){
//                 if (arr1[i]==arr2[j]){
//
//                 Log.e("lll","ll");
//
//                 }
//
//             }
//         }

//        Set<Integer> sameElementSet = getIds(arr1,arr2);
//
//        for (Integer i : sameElementSet) {
//
//            System.out.println(i);
//
//        }
//        for (Integer i:sameElementSet){
//
//
//        }

//for (int i=0;i<list7.length;i++) {
//   // list8.add(list7[i]);
//    t1=list7[i];
//}
//        Log.e("qqqq", ""+list8);


        }

public  void mq(){
        new Thread() {
            @Override
            public void run() {
                try {
String a="1";
if (!a.isEmpty()){
    ss();
}




                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
//    try {
//
//
//                    MQTTService.publish("123");
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
}




public void  ss(){
    MQTTService.publish("123");
}





    public void  getIds(String[] a, String[] b){

        Set<Integer> same = new HashSet<Integer>();  //用来存放两个数组中相同的元素
        Set<String> temp = new HashSet<String>();  //用来存放数组a中的元素

//        for (int i = 0; i < a.length; i++) {
//            temp.add(a[i]);   //把数组a中的元素放到Set中，可以去除重复的元素
//        }

        for (int J = 0; J< b.length; J++) {
            //把数组b中的元素添加到temp中
            //如果temp中已存在相同的元素，则temp.add（b[j]）返回false
            if (!temp.add(b[J])) {
              list4.add(1);
            } else {

               list4.add(0);
            }
        }
     //   }

     Log.e("list4",Arrays.toString(list4.toArray()));
    }


    /* 定义Handler对象 */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        /* 当有消息发送出来的时候就执行Handler的这个方法 */
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            /* 更新UI */
            //  edit_recv.append(strOutput);
            //      Editable text = edit_recv.getText(line);
//            Log.e("IIII", (String) strList.get(0));

            //          Log.e("uuuuu",Arrays.toString(strList.toArray()));
//            Log.e("eeee", (String) strList.toArray()[0]);
            //   Log.e("ee",(String)strList.toArray()[i])
            //   Log.e("mmm",Arrays.toString(partarr));



//            if (socket.isConnected()==true){
//                Toast.makeText(ClientActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
//            }


//
            switch (msg.what) {

                case UPdate:


                    if (strOutput.equals("020304")){

                        p11++;
                        Log.e("p11",""+p11);
                        if (p11>=3){
                            Log.e("p12","12");
                        }
                    }else if (strOutput.equals("020305")){
                        p11=0;
                    }

break;



case  UPdate2:
    if (strOutput.equals("000000000004010201")){

       thread.run();
    }
Log.e("list11", ""+list11);
    if (list11.contains(strOutput)){
        Log.e("32","32");
    }
    break;


case  panduan2:

    btn_connect2.setText("断开连接");
break;


                case panduan:
                    Toast.makeText(ClientActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
//                    if (!MQTTService.str1.isEmpty()&&MQTTService.str1.equals("33")){
//                        send();
//                    }
                    btn_connect.setText("断开连接");

                    break;

//                case  ljcw:
//                    Toast.makeText(ClientActivity.this,"连接错误",Toast.LENGTH_SHORT).show();
//                    break;

                case wflj:
                    Toast.makeText(ClientActivity.this,"无法连接",Toast.LENGTH_SHORT).show();
                  //  btn_connect.setText("连接失败");

                    break;
                case dzcw:
                    Toast.makeText(ClientActivity.this,"地址错误",Toast.LENGTH_SHORT).show();
                    break;
                case ljyc:
                    Toast.makeText(ClientActivity.this,"连接异常",Toast.LENGTH_SHORT).show();
                    break;




            }





                   for (int i = 0; i < partarr.length; i++) {

//<0 错误 ;>=0 正确.
   //                     if (Arrays.binarySearch(new String[]{(String) strList.toArray()[i]}, partarr[i]) < 0) {
                          if ( Arrays.binarySearch(new String[]{ceshiarr[i]}, partarr[i])<0) {
                            //   if (Arrays.binarySearch(new Object[]{list.toArray()[i]}, strList.toArray()[i]) < 0) {
//                if (Arrays.binarySearch(strList.toArray(), new Object[]{strList.toArray()[i]}) < 0) {
                            relist.add("flase");
//                     //   Log.e("XXX", "xx" + );
                        } else {
                            relist.add("true");
                        }
//            Log.e("",""+strList.get(i));

               //     }

                  //     relist.add(String.valueOf(Arrays.equals(new String[]{ceshiarr[i]}, new String[]{partarr[i]}))) ;



              //      Log.e("relist", Arrays.toString(relist.toArray()));

                    txt.setText(Arrays.toString(relist.toArray()));
                    //   Toast.makeText(ClientActivity.this, Arrays.toString(relist.toArray()), Toast.LENGTH_SHORT).show();
                    // Log.e("aaa",Arrays.toString(list.toArray()));

             //       relist.clear();
//
//                    int minlength;
//                    if (list.toArray().length < strList.toArray().length) {
//                        minlength = list.toArray().length;
//                    } else {
//                        minlength = strList.toArray().length;
//                    }
//
//
//                    for (int i = 0; i < minlength; i++) {
//                        Log.e("list1", String.valueOf(Arrays.equals(new String[]{(String) list.toArray()[i]}, new String[]{(String) strList.toArray()[i]})));
//                    }

            }





            listview1.setAdapter(new Dadapter(ClientActivity.this,relist));








        }

         //   Toast.makeText(ClientActivity.this,  relist.toString(),Toast.LENGTH_SHORT).show();

            /* 调试输出 */
//            new Thread()
//            try {
//                Log.i("PDA", "----->" + mBufferedReaderClient.read(buf));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
    //    }
     //   }
    };







    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            // 指定访问的服务器地址是电脑本机
                            .url("http://192.168.31.123/thinkphp1/index.php/Shop/zan")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();



//                   JSONObject jsonObject=new JSONObject(responseData);
//                    device_id = jsonObject.getString("device_id");
//                    Log.e(TAG,"dd"+device_id);

                    parseJSONWithGSON(responseData);

                    //     parseJSONWithJSONObject(responseData);
                    //    parseXMLWithSAX(responseData);
                    //  parseXMLWithPull(responseData);
                    //  showResponse(responseData);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

public class     dqThread  extends  Thread{

                void  pauseThread(){
                    pause=true;
                }
                void  resumeThread(){
                    pause=false;
                    synchronized (lock){
                        lock.notify();
                    }
                }

                void  onPause(){
                    synchronized (lock){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

        public void run() {
                while (true) {
                    while (pause) {
                        onPause();
                    }

                    try {

                        Thread.sleep(2000);
                        test = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08};
                        send();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        }

}


// 502端口号的连接
    @SuppressLint("HandlerLeak")
    public void connect2() {


        //if (socket.isConnected()==false){
        if (false == isConnected2) {
            final String[] str = {null};
            new Thread() {
                public void run() {

                    IPAdr2 = edit_ip2.getText().toString();  //ip地址
                    PORT2 = Integer.parseInt(edit_port2.getText().toString()); //端口号
                    try {

                        /* 建立socket */


                        socket2 = new Socket();
                        SocketAddress socketAddress = new InetSocketAddress(IPAdr2, PORT2);
                        socket2.connect(socketAddress, 2000);

                        /* 输出流 */
                        //      writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        writer = socket2.getOutputStream();
                        /* 输入流 */
                        //       reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        mBufferedReaderClient2 = socket2.getInputStream();


                        msg = new Message();
                        msg.what = panduan2;
                        //  msg.obj=strOutput;
                        handler.sendMessage(msg);

                        /* 调试输出 */
                        System.out.println(socket2.isConnected());
                        Log.i(TAG, "socket2输入输出流获取成功");
                        Log.i(TAG, "检测数据");

                        //                 Log.i("PDA", "----->" + strOutput);

                        /* 读数据并更新UI */

                        /*
                         * 1
                         * */
                        byte[] temp = new byte[1024];

                        //           mBufferedReaderClient.read(temp);
                        //    byte[]buf=null;
                        //     int len=mBufferedReaderClient.read(buf);
                        int ie = 0;
//                        try {
//                            temp=br.readLine();
//                        } catch (IOException e1) {
//                            e1.printStackTrace();
//                        }
                        //     while ((ie=()))
                        while ((ie = mBufferedReaderClient2.read(temp)) != -1) {


                            byte[]bs=new byte[ie];
                            System.arraycopy(temp,0,bs,0,ie);

                            //    byte str[]=bs;

                            strOutput = BinaryToHexString(bs);


                            msg = new Message();
                            msg.what = UPdate2;
                            //        msg.obj = strOutput;
                            handler.sendMessage(msg);

                            Log.i("PDA", "----->" +strOutput);
                            //   Log.e("JJLLHH", "jjllhh" + strOutput);
                            //       strOutput=new String(temp);
                            //把字符串中“ ”去掉


                            //                Log.i("PDA", "----->" + strOutput);

                            String a = "1585193663213041820837";



if (strOutput.substring(0,6).equals("010200")){
    int   disj  = Integer.parseInt(strOutput.substring(6,8));
                 String str=     String.format("%08d",disj);
Log.e("11",str);

}

                        }

                        msg = new Message();
                        msg.what = baocuo2;
                        //  msg.obj=strOutput;
                        handler.sendMessage(msg);


                    } catch (UnknownHostException e) {
                        // Toast.makeText(ClientActivity.this,"无法建立连接：）",Toast.LENGTH_SHORT).show();
                        Log.e("", "wufal");
                        e.printStackTrace();

                        isConnected2 = false;


                    } catch (IOException e) {
                        //    Toast.makeText(ClientActivity.this,"无法建立连接：）",Toast.LENGTH_SHORT).show();
                        Log.e("", "wufaliankjie");
                        //   isConnected=false;

                        msg = new Message();
                        msg.what = wflj;
                        //  msg.obj=strOutput;
                        handler.sendMessage(msg);

                        //          Toast.makeText(ClientActivity.this,"无法连接",Toast.LENGTH_SHORT).show();
                        isConnected2=false;
                        e.printStackTrace();
                        //    isConnected = false;


                    }
                }


            }.start();

            isConnected2 = true;
            //  btn_connect.setText("断开");
        }else {

            isConnected2=false;
            btn_connect2.setText("连接");
           // onDestroy();
            d2();
            Toast.makeText(ClientActivity.this,"已断开连接",Toast.LENGTH_SHORT).show();

        }
    }




    public  void  d1(){   //手动取消socket1
        try {
            /* 关闭socket */
            if(null != socket){
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.getInputStream().close();
                socket.getOutputStream().close();
                socket.close();
            }
        } catch (IOException e) {
            Log.d(TAG,e.getMessage());
        }
        /* 更新UI */
        btn_connect.setText("连接");
        // edit_recv.setText("");


        Log.e("d1","d1执行了");
    }


    public  void  d2(){//手动取消socket2
        try {
            /* 关闭socket */
            if(null != socket2){
                socket2.shutdownInput();
                socket2.shutdownOutput();
                socket2.getInputStream().close();
                socket2.getOutputStream().close();
                socket2.close();
            }
        } catch (IOException e) {
            Log.d(TAG,e.getMessage());
        }
        /* 更新UI */
        btn_connect2.setText("连接");
        // edit_recv.setText("");


        Log.e("d2","d2执行了");
    }


    /* 连接按钮处理函数：建立Socket连接 */
    @SuppressLint("HandlerLeak")
    public void connect() {


        //if (socket.isConnected()==false){
        if (false == isConnected) {
            final String[] str = {null};
            new Thread() {
                public void run() {



                    IPAdr = edit_ip.getText().toString();  //ip地址
                    PORT = Integer.parseInt(edit_port.getText().toString()); //端口号
                    try {

                        /* 建立socket */

                        //   socket = new Socket(IPAdr, PORT);
                        socket = new Socket();
                        SocketAddress socketAddress = new InetSocketAddress(IPAdr, PORT);
                        socket.connect(socketAddress, 2000);

                        /* 输出流 */
                        //      writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        writer = socket.getOutputStream();
                        /* 输入流 */
                        //       reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        mBufferedReaderClient = socket.getInputStream();
                        //     isr=new InputStreamReader(mBufferedReaderClient);
                        //    br=new BufferedReader(isr);
//                        int line=0;
//                        byte[]bu=new byte[mBufferedReaderClient.available()];
//                        while ((line=mBufferedReaderClient.read(bu))!=-1){
////
//                            strOutput=BinaryToHexString(bu);
//                                 }


                        msg = new Message();
                        msg.what = panduan;
                        //  msg.obj=strOutput;
                        handler.sendMessage(msg);

                        /* 调试输出 */
                        System.out.println(socket.isConnected());
                        Log.i(TAG, "输入输出流获取成功");
                        Log.i(TAG, "检测数据");

                        //                 Log.i("PDA", "----->" + strOutput);

                        /* 读数据并更新UI */






                        byte[] temp = new byte[1024];

             //           mBufferedReaderClient.read(temp);
                        //    byte[]buf=null;
                        //     int len=mBufferedReaderClient.read(buf);
                        int ie = 0;
//                        try {
//                            temp=br.readLine();
//                        } catch (IOException e1) {
//                            e1.printStackTrace();
//                        }
                        //     while ((ie=()))
                       while ((ie = mBufferedReaderClient.read(temp)) != -1) {



                           byte[]bs=new byte[ie];
                           System.arraycopy(temp,0,bs,0,ie);

                       //    byte str[]=bs;

                            strOutput = BinaryToHexString(bs);


                            msg = new Message();
                            msg.what = UPdate;
                    //        msg.obj = strOutput;
                            handler.sendMessage(msg);

                            Log.e("PDA", "----->" +strOutput);
                            //   Log.e("JJLLHH", "jjllhh" + strOutput);
                            //       strOutput=new String(temp);
                            //把字符串中“ ”去掉


                            //                Log.i("PDA", "----->" + strOutput);

                            String a = "1585193663213041820837";



                        if (strOutput.length()==28&&strOutput.contains("A00C")){
                            position=position+1;

                            send();
                          //  Log.e("","天线"+position/2);
                        }else if (strOutput.length()==12&&strOutput.substring(6,8).equals("80")&&!strOutput.equals("A004017410D7")){
                            position=position+0;
                            send();
                            Log.e("","反正我也运行了");

                        }

//if (strOutput.contains("A00C")){
//                            Log.e("","true");
//                            Log.e("",""+strOutput.length());
//}





                       if (strOutput.length()>53) {
                           sss();
                       }

             //          count=0;




                                }


                        msg = new Message();
                        msg.what = baocuo;
                        //  msg.obj=strOutput;
                        handler.sendMessage(msg);


                    } catch (UnknownHostException e) {
                        // Toast.makeText(ClientActivity.this,"无法建立连接：）",Toast.LENGTH_SHORT).show();
                        Log.e("", "wufal");
                        e.printStackTrace();

                           isConnected = false;


                    } catch (IOException e) {
                        //    Toast.makeText(ClientActivity.this,"无法建立连接：）",Toast.LENGTH_SHORT).show();
                        Log.e("", "wufaliankjie");
                        //   isConnected=false;

//                        try {
//                            writer.close();
//                            mBufferedReaderClient.close();
//                            socket.close();
//                        } catch (IOException e1) {
//                            e1.printStackTrace();
//                        }

                        msg = new Message();
                        msg.what = wflj;
                        //  msg.obj=strOutput;
                        handler.sendMessage(msg);

                        //          Toast.makeText(ClientActivity.this,"无法连接",Toast.LENGTH_SHORT).show();
                        isConnected=false;
                        e.printStackTrace();
                        //    isConnected = false;




                    }
                }


            }.start();


            isConnected = true;
          //  btn_connect.setText("断开");
        }else {

            isConnected=false;
            btn_connect.setText("连接");
            //onDestroy();
            d1();
Toast.makeText(ClientActivity.this,"已断开连接",Toast.LENGTH_SHORT).show();


        }
    }



    public void sss(){
        list10.add(strOutput);

        if (list10.size()>0) {
            p2.append(list10.get(list.size() ));
            Log.e("2252", p2.toString());
            //   }
        }


        int len = p2.toString().length();

        int sub = 54;
        if (len/sub!= 0) {

            for (int i = 0; i < p2.toString().length() - (len /sub); i += 54) {

                //    while (true) {
                //    if (start >= strOutput.length())


                //      for (int l=0;l<strOutput.length();l++) {


                tp = p2.toString().substring(i, i + 54);


                st = tp.substring(18, 42);
                strList.add(st);

//                asciiToString(strList.toString());

                Log.e("zxcc",strList.toString());

             //   Gson g=new Gson();
               // String jsonString=g.toJson(strList);

                String json="[{'name':'x16toString((String) strList.get(0))','age':13},{'name':'jack','age':13}]";
                JSONArray a = null;
                try {
                    a = new JSONArray(json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
              Log.e("json",a.toString());
//Log.e("jsonceshi",x16toString((String) strList.get(0)));



                JSONArray array =new JSONArray();
                JSONObject object =new JSONObject();
                JSONObject object1 =new JSONObject();
                JSONObject obj= new JSONObject();
                try {
                    object.put("item1","value1");
                    object.put("age",12);
                    object.put("name","tom");
                    object1.put("item2","value2");
                    object1.put("age",12232);
                    object1.put("name","tom");
                    array.put(object);
                    array.put(object1);
                    obj.put("name",array);
              //      System.out.println(obj.toString());
                    Log.e("json1",array.toString());
                Log.e("jsonceshi",obj.toString());

                }catch (Exception e){

                }








                //  Message msg=handler.obtainMessage();


                //      Log.e("kkjkj",  st );

                //        strList.add(st);
                //      Log.e("PDA", Arrays.toString(strList.toArray()));
                //    Log.e("PDA", tp);

//                               firstList.add(tp);
//                              String s="";
//
//                               for (int t = 0; t< firstList.size(); t++) {
//                                                    if (s=="") {
//                                             s= (String) firstList.get(t);}else {
//                                                        s=s+""+firstList.get(t);
//
//
//                                    Log.e("110", s);

                //   Log.e("yui",firstList.toString());


            }
        }
for (int i=0;i<strList.size();i++){
          zx=x16toString((String) strList.get(i));
          Log.e("String",zx);
}
if (!zx.isEmpty()){
            MQTTService.publish("123");
}

    }


    public static String x16toString(String x16 ){
        if(x16==null || "".equals(x16.trim())){
            return "";
        }
        String tempStr = "";
        byte[] b = new byte[x16.length()/2];
        for(int i=0; i<x16.length()/2; i++){
            tempStr = x16.substring(i*2, i*2+2);
            int temp = Integer.parseInt(tempStr, 16);
            b[i] = (byte) temp;
        }
        String restr = new String(b);
        return restr;
    }





        //将字节数组转换为16进制字符串
        public static String BinaryToHexString(byte[] bytes) {
            String hexStr = "0123456789ABCDEF";
            String  result = "";
            String hex = "";
            for (byte b : bytes) {
                hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
                hex += String.valueOf(hexStr.charAt(b & 0x0F));
              //  result += hex + " ";
                result+=hex;
            }
            return result;

        }


    public static void hexToBinary(String hex) {
        int decimal = Integer.parseInt(hex, 16);
        Log.e("9",""+decimal);
        String binary = Integer.toBinaryString(decimal);

    }



    public static byte[] hexStrToBinaryStr(String hexString) {


        hexString = hexString.replaceAll(" ", "");

        int len = hexString.length();
        int index = 0;

        byte[] bytes = new byte[len / 2];

        while (index < len) {

            String sub = hexString.substring(index, index + 2);

            bytes[index/2] = (byte)Integer.parseInt(sub,16);

            index += 2;
        }


        return bytes;
    }

    /**
     * 将字节数组转换成十六进制的字符串
     *
     * @return
     */





    class  NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String data=intent.getStringExtra("zhi1");
            String a="ceshiyuju";

            if (MQTTService.str1.equals("33")){
                //       byte[] test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
//                    //    byte[] test=hexStringToBytes
               send();
//                ms[0]=(byte)0xA0;
//                ms[1]=(byte)0x03;
//                ms[2]=(byte)0x01;
//                ms[3]=(byte)0x90;
//                ms[4]=(byte)0xCC;
           //     Toast.makeText(ClientActivity.this,Arrays.toString(test),Toast.LENGTH_SHORT).show();

            }else if (MQTTService.str1.equals("44")){
                test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x90,(byte)0xCC};
            }



            if (MQTTService.str1.equals("")){
                     thread.pauseThread();
                     //*******发送DO指令



                thread.resumeThread();

            }








//if (data.equals("ceshiyuju") ){
//    Toast.makeText(Main2Activity.this,MQTTService.str1,Toast.LENGTH_SHORT).show();
//
//}

//
//            if (MQTTService.str1.equals("33")){
//           Toast.makeText(Main2Activity.this,"33",Toast.LENGTH_SHORT).show();
//       }else if (MQTTService.str1.equals("44")){
//           Toast.makeText(Main2Activity.this,"44",Toast.LENGTH_SHORT).show();
//       }
//
        }
    }










    /* 发送按钮处理函数：向输出流写数据 */
    public void send() {
//        if (isConnected==false) {
//
//            Toast.makeText(ClientActivity.this, "请连接", Toast.LENGTH_SHORT).show();
//        } else {


            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        /* 向输出流写数据 */


                        //    byte[] test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
                        //    byte[] test=hexStringToBytes


                        //  byte[] bS=edit_send.getText().toString().getBytes();
                        //     bS=edit_send.getText().toString();

                        //    bytesToHexFun1(bytes);

                        ///  System.out.println("11111"+sb);


                        //  writer.write(String.valueOf(bytes));

                    //    toHexString(sb);
//String cm="A0 03 01 72 EA";
//                        byte[] test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
                      //  test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
                        ms[0]=(byte)0xA0;
                        ms[1]=(byte)0x03;
                        ms[2]=(byte)0x01;
                        ms[3]=(byte)0x90;
                        ms[4]=(byte)0xCC;
                        String cm = edit_send.getText().toString();

                        byte[] cm2 = hexStrToBinaryStr(cm);
                     //   test=new byte[]{(byte)0xA0,(byte)0x04,(byte)0x01,(byte)0x80,(byte)0x01,(byte)0xDA};
//                        test=new byte[]{(byte)0x01,(byte)0x02,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x08,(byte)0x79,(byte)0xCC};

                        OutputStream socketWriter = socket.getOutputStream();
                          socketWriter.write(test);
//                        socketWriter.flush();

                          ///  socketWriter.write(hexStrToBinaryStr(list7[position]));
                            socketWriter.flush();
                         // Thread.sleep(1);
                        if (position ==8){
                            position=0;
                            list10.clear();
                            p2.delete(0,p2.length());
                            strList.clear();

                        }

                 //        writer.write(test);

                        //     writer.write(ByteUtil.BinaryToHexString(bS));
//        //    writer.write(String.valueOf(msg));
//           // writer.write(String.valueOf(sb));


                   //      writer.flush();





                        /* 更新UI */
                        //        edit_send.setText("");

//                        socketWriter.close();
//                        socket.close();

                    }
                    catch (UnknownHostException e){
                        e.printStackTrace();
                    }

                    catch (IOException e) {
                        e.printStackTrace();

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();

        }


//    }




    /* 发送按钮处理函数：向输出流写数据 */
    public void send2() {
//        if (isConnected==false) {
//
//            Toast.makeText(ClientActivity.this, "请连接", Toast.LENGTH_SHORT).show();
//        } else {


        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    /* 向输出流写数据 */


                    //    byte[] test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
                    //    byte[] test=hexStringToBytes


                    //  byte[] bS=edit_send.getText().toString().getBytes();
                    //     bS=edit_send.getText().toString();

                    //    bytesToHexFun1(bytes);

                    ///  System.out.println("11111"+sb);


                    //  writer.write(String.valueOf(bytes));

                    //    toHexString(sb);
//String cm="A0 03 01 72 EA";
//                        byte[] test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
                    //  test=new byte[]{(byte)0xA0,(byte)0x03,(byte)0x01,(byte)0x72,(byte)0xEA};
                    ms[0]=(byte)0xA0;
                    ms[1]=(byte)0x03;
                    ms[2]=(byte)0x01;
                    ms[3]=(byte)0x90;
                    ms[4]=(byte)0xCC;
                    String cm = edit_send.getText().toString();

                    byte[] cm2 = hexStrToBinaryStr(cm);
                    //   test=new byte[]{(byte)0xA0,(byte)0x04,(byte)0x01,(byte)0x80,(byte)0x01,(byte)0xDA};
//                        test=new byte[]{(byte)0x01,(byte)0x02,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x08,(byte)0x79,(byte)0xCC};

                    OutputStream socketWriter = socket2.getOutputStream();
                    socketWriter.write(test);
//                        socketWriter.flush();

                    ///  socketWriter.write(hexStrToBinaryStr(list7[position]));
                    socketWriter.flush();
                    // Thread.sleep(1);
                    if (position ==8){
                        position=0;
                        list10.clear();
                        p2.delete(0,p2.length());
                        strList.clear();

                    }

                    //        writer.write(test);

                    //     writer.write(ByteUtil.BinaryToHexString(bS));
//        //    writer.write(String.valueOf(msg));
//           // writer.write(String.valueOf(sb));


                    //      writer.flush();





                    /* 更新UI */
                    //        edit_send.setText("");

//                        socketWriter.close();
//                        socket.close();

                }
                catch (UnknownHostException e){
                    e.printStackTrace();
                }

                catch (IOException e) {
                    e.printStackTrace();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }










    @Override
    protected void onDestroy() {
        try {
            /* 关闭socket */
            if(null != socket){
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.getInputStream().close();
                socket.getOutputStream().close();
                socket.close();
            }
        } catch (IOException e) {
            Log.d(TAG,e.getMessage());
        }
        /* 更新UI */
        btn_connect.setText("连接");
       // edit_recv.setText("");


        Log.e("destroy","destroy执行了");


//        try {
//            /* 关闭socket */
//            if(null != socket2){
//                socket2.shutdownInput();
//                socket2.shutdownOutput();
//                socket2.getInputStream().close();
//                socket2.getOutputStream().close();
//                socket2.close();
//            }
//        } catch (IOException e) {
//            Log.d(TAG,e.getMessage());
//        }
//        /* 更新UI */
//        btn_connect2.setText("连接");
//        // edit_recv.setText("");
//
//
//        Log.e("destroy","destroy执行了");
        super.onDestroy();
    }






    private void parseJSONWithGSON(String jsonData) {
        Gson gson=new Gson();
        List<App>appList=gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
        for (App app:appList){
            //   Log.d("CkaActivity", app.getPhone());
//            if (app.getPhone().equals(NameSaveSp.instance().getNameValue("age"))) {
//                Log.d("CkaActivity", "age is" + app.getAge());
//                Log.d("CkaActivity", "tel is" + app.getAddress());
//                Log.d("CkaActivity", "sex is" + app.getUsername());
            list.add(app.getId());
            Log.e("getid",""+app.getId());
//                age.setText(app.getAge());
//                tel.setText(app.getAddress());
//                username.setText(app.getUsername());
            //    device_id=app.getDevice_id();
            //  responseText.setText(app.getDevice_id());



        }
    }






}
